<template>
    <div class="back-box" v-if="isShow">
        <div class="back-info">
            <el-icon size="16" color="#4c4c4c" class="cursor" @click="props.closeChat" v-if="props.isBack"><ArrowLeftBold /></el-icon>
            <div class="user-item">
                <div class="user-picture">
                    <div class="pic" v-if="userInfo && userInfo.avatar_url">
                        <img :src="userInfo.avatar_url" alt="">
                    </div>
                    <el-icon v-else size="26" color="#fff"><UserFilled /></el-icon>
                </div>
                <div class="user-msg">
                    <span class="user-name">{{userInfo.name}}</span>
                    <!-- <span class="msg">上线</span> -->
                </div>
            </div>
        </div>
        <el-dropdown trigger="click">
            <el-icon size="16" color="#4c4c4c" class="cursor"><MoreFilled /></el-icon>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item>{{$t('chat-txt.txt-8')}}</el-dropdown-item>
                    <el-dropdown-item>{{$t('chat-txt.txt-9')}}</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
    <div class="chat-list" v-if="isShow" ref="chatListRef">
        <el-scrollbar ref="chatScrollbar" class="chat-messages" @scroll="handleScroll" height="100%">
            <p class="tips">{{$t('chat-txt.txt-10')}}</p>
            <p class="tips"><i>{{$t('chat-txt.txt-11')}}</i></p>
            <!-- 加载历史提示 -->
            <div v-if="isLoading" class="loading-indicator">
                <el-icon size="18"><Loading /></el-icon>
                <span class="loading-text">{{ $t('chat-txt.txt-12') }}</span>
            </div>
            <div v-for="(item, index) in groupedMessages" :key="index">
                <div class="msg-item time">{{ index }}</div>
                <div class="msg-item msg" :class="subItem.sender_id == otherUserId ? 'other-user-msg' : ''" @click="isChooseChat = true" v-for="(subItem, subIndex) in item" :key="subIndex">
                    <div class="msg-top" :class="subItem.sender_id == otherUserId ? 'msg-top-other' : ''">
                        <div class="user-item" v-if="subItem.sender_id == otherUserId">
                            <div class="user-picture">
                                <div class="pic" v-if="subItem.sender && subItem.sender.avatar_url">
                                    <img :src="subItem.sender.avatar_url" alt="">
                                </div>
                                <el-icon v-else size="26" color="#fff"><UserFilled /></el-icon>
                            </div>
                            <div class="user-msg">
                                <span class="user-name">{{subItem.sender.name}}</span>
                            </div>
                        </div>
                        <span class="msg-time">
                            {{formatOnlyTime(subItem.created_at_formatted)}}
                            <el-radio v-model="chooseChat" size="small" v-if="isChooseChat"></el-radio>
                        </span>
                    </div>
                    <span class="msg-text">{{ subItem.content }}</span>
                </div>
            </div>
        
            <!-- 已加载全部历史 -->
            <div v-if="!hasMoreHistory && pagination.totalPages > 1" class="all-loaded">
                {{$t('chat-txt.txt-13')}}
            </div>
        </el-scrollbar>
        
        
    </div>
    <div class="chat-send-box" v-if="isShow">
        <el-input v-model="chatText" :rows="4" type="textarea" :placeholder="$t('chat-txt.txt-14')" @keyup.enter="chatSendHandle" />
        <div class="tools-chat">
            <el-icon size="20" color="#4c4c4c"><Cherry /></el-icon>
            <el-icon size="20" color="#4c4c4c" @click="chatSendHandle"><Promotion /></el-icon>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, nextTick } from 'vue'
import { ElScrollbar } from 'element-plus';
import CourseService from '@/api/course'
import { formatTime, formatOnlyTime } from '@/utils/global'
const props = defineProps<{
    isBack?: Boolean
    closeChat?: () => void
}>()

const chooseChat = ref(false)
const isChooseChat = ref(false)
const chatText = ref('')
const isShow = ref(false)
const otherUserId = ref(0)
const userInfo = ref(null)
const initDialog = (id: number, info: any) => {
    isShow.value = true
    userInfo.value = info
    otherUserId.value = id
    pagination.value = {
        page: undefined,
        limit: 20,
        total: 0,
        totalPages: 0,
    }
    hasMoreHistory.value = true;
    conversationList.value = [];
    // 这里可以添加初始化聊天对话的逻辑
    getUserConversation()
    // 每10秒刷新一次
    // setInterval(() => {
    //     pagination.value = {
    //         page: 1,
    //         limit: 10,
    //         total: 0,
    //         totalPages: 0,
    //     }
    //     hasMoreHistory.value = true;
    //     conversationList.value = [];
    //     getUserConversation();
    // }, 10000)
}
// 分页器
import type { Pagination } from '@/types/global'
const pagination = ref<Pagination>({
    page: undefined,
    limit: 20,
    total: 0,
    totalPages: 0,
})
// 获取用户沟通记录
const loading = ref(false)
const conversationList = ref([])
const getUserConversation = () => {
    // 这里可以添加获取用户对话的逻辑
    loading.value = true
    isLoading.value = true;
    const searchData = {
        id: otherUserId.value,
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    CourseService.getCommunicationConversation(searchData)
        .then(res => {
            conversationList.value = [...res.dataList, ...conversationList.value]
            pagination.value = res.pagination || pagination.value
            if(pagination.value.page == 1){
                readAction();
                nextTick(() => {
                    scrollToBottom(chatListRef.value)
                });
            }
        })
        .finally(() => {
            loading.value = false
            isLoading.value = false
        })
}
// 按日期分组聊天记录
const groupedMessages = computed(() => {
  // 创建一个空对象用于存储分组后的消息
  const groups = {};
    const tempList = [...conversationList.value].sort((a, b) => {
        const timeA = new Date(a.created_at_formatted).getTime(); // 转换为时间戳
        const timeB = new Date(b.created_at_formatted).getTime();
        return timeA - timeB; // 倒序排列（大的时间戳在前）
    });
  // 遍历所有消息
  tempList.forEach((message) => {
    // 提取日期部分（YYYY-MM-DD）
    const date = message.created_at_formatted.split(' ')[0];
    
    // 如果该日期分组不存在，则创建一个
    if (!groups[date]) {
      groups[date] = [];
    }
    
    // 将消息添加到对应的日期分组中
    groups[date].push(message);
  });
  
  return groups;
});
// 标记为已读
const readAction = () => {
    CourseService.postCommunicationMarkAsRead({other_user_id: otherUserId.value}).then(() => {})
}
// 发送聊天消息
const chatSendHandle = () => {
    const paramsData = {
        receiver_id: otherUserId.value,
        content: chatText.value,
    }
    CourseService.postCommunication(paramsData)
        .then(res => {
            chatText.value = ''
            pagination.value = {
                page: undefined,
                limit: 20,
                total: 0,
                totalPages: 0,
            }
            conversationList.value = []
            hasMoreHistory.value = true;
            nextTick(() => {
                getUserConversation()
            })
        })
        .finally(() => {
            
        })
}
defineExpose({
    initDialog,
})

const chatListRef = ref(null);
// 滚动到最底部的通用方法
const scrollToBottom = (el) => {
    chatScrollbar.value.wrapRef.scrollTop = chatScrollbar.value.wrapRef.scrollHeight;
//     console.log('el', el.scrollHeight);
//   if (el) {
//     // 方法1：直接设置scrollTop为scrollHeight
//     el.scrollTop = el.scrollHeight;
    
//     // 方法2：使用scrollTo API（更灵活）
//     // el.scrollTo({
//     //   top: el.scrollHeight,
//     //   behavior: 'smooth' // 平滑滚动
//     // });
//   }
};
// 聊天滚动容器
const chatScrollbar = ref(null);
const isLoading = ref(false);
const hasMoreHistory = ref(true);
// 处理滚动事件 - 滚动到顶部加载更多
const handleScroll = () => {
  if (!chatScrollbar.value) return;
  
  // 获取滚动容器的滚动位置
  const scrollTop = chatScrollbar.value.wrapRef.scrollTop;
  
  // 当滚动到顶部附近且不在加载中且还有更多历史时
  if (scrollTop <= 20 && !isLoading.value && hasMoreHistory.value) {
    console.log("加载更多数据")
    loadMoreHistory();
  }
};
// 加载更多历史记录
const loadMoreHistory = () => {
  pagination.value.page--;
  if (pagination.value.page < 1) {
    hasMoreHistory.value = false;
    return;
  }
  getUserConversation();
//   loadMessagePage(pagination.value.page);
};
</script>

<style lang="less" scoped>
/* 已加载全部 */
.all-loaded {
  text-align: center;
  padding: 10px;
  color: #999;
  font-size: 12px;
}
/* 加载指示器 */
.loading-indicator {
  text-align: center;
  padding: 10px 0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text {
  margin-left: 8px;
  font-size: 14px;
}
.back-box {
    border-bottom: 1px solid #dee2e6 !important;
    padding: 0 10px;
    font-size: 15px;
    color: #4c4c4c;
    background-color: #eff1f3;
    min-height: 44px;

    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .cursor {
        cursor: pointer;
    }

    .back-info {
        display: flex;
        align-items: center;
        gap: 4px;
    }
}

.user-item {
    border-bottom: 1px solid rgba(0, 0, 0, 0.085);
    padding: 8px;

    display: flex;
    align-items: center;

    &:last-child {
        border: none;
    }

    .user-picture {
        border-radius: 50%;
        background-color: #e5e5e5;
        width: 38px;
        height: 38px;

        display: flex;
        align-items: center;
        justify-content: center;
    }

    .user-msg {
        padding-left: 8px;
        flex-grow: 1;
        color: #4c4c4c;
        font-size: 15px;
        line-height: 1.666;

        .user-name {
            font-weight: bold;
            display: block;
        }

        .msg {
            display: block;
        }
    }

    .time {
        font-size: 12px;
        color: #4c4c4c;
    }
}

.chat-list {
    padding: 15px;
    height: 100%;
    overflow-y: auto;
    background-color: #f8f9fa;

    .tips {
        font-size: 12px;
        color: #4c4c4c;
        text-align: center;
        line-height: 1.75;

        &:first-child {
            margin-top: 15px;
        }
    }

    .msg-item {
        margin-bottom: 8px;
        color: #212529;

        &.time {
            margin-top: 15px;
            font-size: 15px;
            text-align: center;
        }

        &.msg {
            border-radius: 4px;
            border: 2px solid #d5d5d5;
            padding: 8px;
            background-color: #dee2e6;
            cursor: pointer;
            transition: all 0.35s ease-in-out;

            display: flex;
            flex-direction: column;
            .msg-top{
                
            }
            .msg-top-other{
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                align-content: center;
                .user-item{
                    border-bottom: 0;
                    padding-left: 0;
                }
            }
            .msg-time {
                text-align: right;
                font-size: 12px;
                line-height: 1.75;

                display: flex;
                align-items: center;
                justify-content: flex-end;
                gap: 10px;
            }

            .msg-text {
                font-size: 15px;
                line-height: 1.75;
            }

            &:hover {
                filter: drop-shadow(2px 2px 2px rgba(0, 0, 0, 0.3));
                border-color: #fb8b24;
            }
        }
        &.other-user-msg {
            border: 2px solid #D5D5D5;
            background-color: #ffffff;
        }
    }

    .tips + .msg-item {
        margin-top: 30px;
    }
}

.chat-send-box {
    border-top: 1px solid #d5d5d5;
    padding: 15px;

    display: flex;

    .el-textarea {
        margin-right: 15px;
        flex-grow: 1;
        font-size: 15px;

        --el-input-border-radius: 0;
        --el-input-focus-border: #f06423;
        --el-input-focus-border-color: #f06423;
    }

    .tools-chat {
        padding: 10px 0;
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .el-icon {
            cursor: pointer;
            transition: color 0.35s ease-in-out;

            &:hover {
                color: #f06423;
            }
        }
    }
}
</style>
